Sending mail without user interaction in Android
You have learned Android Intent, which is an object carrying an intent ie. message from one component to another component within the application or outside the application.
As such you do not need to develop your email client from scratch because they are already available like Gmail and K9mail. But you will need to send an Email from your Android application, where you will have to write an Activity that needs to launch an email client and sends an email using your Android device. For this purpose, your Activity will send an ACTION_SEND along with an appropriate data load, to the Android Intent Resolver. The specified chooser gives the proper interface for the user to pick how to send your email data.
Here I am creating an example of send email without the interaction of the user in android
- Create an android project and SDK must be greater than 10
- Download three jar file
- mail.jar
- activation.jar
- additionnal.jar
- Add jar file in your libs folder and add it in the build path.
- Add permission in AndroidManifest.xml file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androimail"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.androimail.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Add the following code in MainActicvity.class
package com.example.androimail;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
Button button;
GMailSender sender;
@SuppressLint("NewApi")
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.mybtn);
// Add your mail Id and Password
sender = new GMailSender("my mail", "my password");
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.
Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
try { new MyAsyncClass().execute(); }
catch (Exception ex)
{ Toast.makeText(getApplicationContext(), ex.toString(), 100).show(); } } });
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it // is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
class MyAsyncClass extends AsyncTask<Void, Void, Void> {
ProgressDialog pDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.show();
}
@Override
protected Void doInBackground(Void... mApi) {
try {
// Add subject, Body, your mail Id, and receiver mail Id.
sender.sendMail("Subject", " body", "from Mail", "to mail");
}
catch (Exception ex) {
} return null; }
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pDialog.cancel();
Toast.makeText(getApplicationContext(), "Email send", 100).show();
} } }
Create class GMailSender, java and extends javax.mail.Authenticator. You are able to use any package name. For this extends, you need to add these three jar in your project libraries.
Add following code
package com.example.androimail;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Security;
import java.util.Properties;
public class GMailSender extends javax.mail.Authenticator {
private String mailhost = "smtp.gmail.com";
private String user;
private String password;
private Session session;
static {
Security.addProvider(new JSSEProvider()); }
public GMailSender(final String user, final String password) {
this.user = user;
this.password = password;
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", mailhost);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
props.put("mail.smtp.starttls.enable", "true");
props.setProperty("mail.smtp.quitwait", "false");
session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
});
session = Session.getDefaultInstance(props, this);
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
public synchronized void sendMail(String subject, String body,
String sender, String recipients) throws Exception {
MimeMessage message = new MimeMessage(session);
DataHandler handler = new DataHandler(new ByteArrayDataSource(
body.getBytes(), "text/plain"));
message.setSender(new InternetAddress(sender));
message.setSubject(subject);
message.setDataHandler(handler);
if (recipients.indexOf(',') > 0)
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(recipients));
else
message.setRecipient(Message.RecipientType.TO, new InternetAddress(
recipients));
Transport.send(message);
}
public class ByteArrayDataSource implements DataSource {
private byte[] data;
private String type;
public ByteArrayDataSource(byte[] data, String type) {
super();
this.data = data;
this.type = type; }
public ByteArrayDataSource(byte[] data) {
super();
this.data = data;
}
public void setType(String type) {
this.type = type;
}
public String getContentType() {
if (type == null)
return "application/octet-stream";
else
return type;
}
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(data);
}
public String getName() {
return "ByteArrayDataSource";
}
public OutputStream getOutputStream() throws IOException {
throw new IOException("Not Supported");
}
}
}
Create an JSSEProvider class and paste following code
package com.example.androimail;
import java.security.AccessController;
import java.security.Provider;
public class JSSEProvider extends Provider {
public JSSEProvider() {
super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");
AccessController
.doPrivileged(new java.security.PrivilegedAction<Void>() {
public Void run() {
put("SSLContext.TLS",
"org.apache.harmony.xnet.provider.jsse.SSLContextImpl");
put("Alg.Alias.SSLContext.TLSv1", "TLS");
put("KeyManagerFactory.X509",
"org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl");
put("TrustManagerFactory.X509",
"org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl");
return null;
}
}); }
}
Now run your application
Hemant Kumar Kushwaha
20-Oct-2018// Add your mail Id and Password
sender = new GMailSender("my mail", "my password");
Can I use this line without a password, as I am building a shopping app for my project where I want to send an email to the user whenever the user buys an item?
Kapil Rana
28-Aug-2018no email received .
i have also create a new account .
Saifali Pundir
01-Dec-2017I am getting javax.mail.AuthenticationFailedException exception please help me
Shubhasish Routray
19-Sep-2017marry desuza
12-Jul-2017MANISH KUMAR
07-Mar-2017Boon Gong
13-Sep-2016-BG
shailesh R
06-Jul-2016shailesh R
06-Jul-2016Manoj Pandey
24-Jun-2016Teyim Pila
24-Jun-2016Manoj Pandey
13-Jun-2016Sumit Kumawat
10-Jun-2016zeeshan jiwani
25-Apr-2016Manoj Pandey
25-Apr-2016zeeshan jiwani
25-Apr-2016Manoj Pandey
13-Apr-2016Sakshi Seth
12-Apr-2016Manoj Pandey
19-Oct-2015Jonás Perusquía
18-Oct-2015My problem is that no email is recieved (unsafe apps enabled and two-step auth disabled).
Also inside MyAsyncClass class I wrote:
To do:
I suppose this is valid, right?
Even if I have no errors, no email is recieved :(
Could you please help me? Thanks in advance
Manoj Pandey
22-Jun-2015nhel clamor
19-Jun-2015nhel clamor
18-Jun-2015nhel clamor
18-Jun-2015John Smith
18-Jun-2015Join MindStick Forum
nhel clamor
17-Jun-2015John Smith
01-May-2015Happy Coding!!!
wim soutendijk
30-Apr-2015wim soutendijk
29-Apr-2015// Add your mail Id and Password
sender = new GMailSender("my mail", "my password");
sender.sendMail("Subject", " body", "from Mail", "to mail");
Manoj Pandey
29-Apr-2015I have checked my code which are working correctly.
I don't know you are giving right mail Id or password , but if you are giving right information then you have need to check your account security. May be you have find a mail from Google for check access your account. Now tell him this was you which are accessing google account.
wim soutendijk
28-Apr-2015Manoj Pandey
28-Apr-2015@Override
protectedvoid onPostExecute(Void result) {
super.onPostExecute(result);
pDialog.cancel();
Toast.makeText(MainActivity.this,"Email send",100).show();
}
wim soutendijk
27-Apr-2015wim soutendijk
26-Apr-2015